/*
 * @lc app=leetcode.cn id=766 lang=typescript
 *
 * [766] 托普利茨矩阵
 */

// @lc code=start
function isToeplitzMatrix(matrix: number[][]): boolean {
    // 最后一个数字不需要检查
    let maxX = matrix[0].length - 1;
    let maxY = matrix.length - 1;

    const isValidArray = (x: number, y: number) => {
        let temp = matrix?.[y]?.[x];
        while (typeof temp === "number") {
            let newTemp = matrix?.[y]?.[x];
            if (typeof newTemp !== "number") return true;
            if (newTemp !== temp) {
                return false;
            }
            y++;
            x++;
        }
        return true;
    };

    for (let index = 0; index < maxX; index++) {
        if (!isValidArray(index, 0)) return false;
    }
    for (let index = 1; index < maxY; index++) {
        if (!isValidArray(0, index)) return false;
    }
    return true;
}
// @lc code=end
